<?php
/**
 * Created by PhpStorm.
 * User: jaylen
 * Date: 2020-10-20
 * Time: 21:38
 */

namespace app\common\job;


use app\api\model\mp\v1\OrderSubscribeMessage;
use app\api\model\mp\v1\TNShopOrderNotifyTemplateMessage;
use app\common\enum\OrderEnum;
use app\common\enum\OrderType;
use app\common\model\ShopProduct;
use function PHPSTORM_META\type;
use think\queue\Job;
use app\common\model\Order as OrderModel;

class PaySuccessNotifyQueue
{
    /**
     * fire是消息队列默认调用的方法
     * @param Job $job 当前的任务对象
     * @param array|mixed $data 发布任务时自定义的数据
     */
    public function fire(Job $job, $data)
    {
        //有效消息到达消费者时可能已经不再需要执行了
        if (!$this->checkJob($data)) {
            $job->delete();
            return;
        }
        //执行业务处理
        if ($this->doJob($data)) {
            $job->delete();//任务执行成功后删除
            echo '[支付成功通知]订单'.$data['order_no'].'通知成功'.PHP_EOL;
        } else {
            //检查任务重试次数
            if ($job->attempts() > 3) {
                echo '[支付成功通知]订单'.$data['order_no'].'通知失败，达到最大重试数'.PHP_EOL;
                $job->delete();
            }
        }
    }

    /**
     * 接收队列消息的失败回调和告警
     * @param $e 消息队列出错的相关信息
     */
    public function failed($e)
    {
        print_r('消息队列出错，出错信息如下');
        var_dump($e);
    }

    /**
     * 简单当前订单是否需要执行本消息
     * @param array|mixed $data 发布任务时自定义的数据
     * @return boolean 任务执行的结果
     */
    private function checkJob($data)
    {
        $order_no = $data["order_no"];

        // 判断订单是否存在或者是否为已提交状态
        if (OrderModel::checkOrderStatusByOrderNo($order_no, OrderEnum::CREATE_ORDER)) {
            return true;
        }

        (new OrderModel())->db()->getConnection()->close();
        return false;
    }

    /**
     * 根据消息中的数据进行实际的业务处理
     */
    private function doJob($data)
    {
        // 实际业务流程处理
        $order_no = $data["order_no"];
        $transaction_id = $data['transaction_id'];
        $is_send_template = $data['is_send_template'];
        $attach = $data['attach'];

        // 更新订单信息
        OrderModel::updateByOrderNo($order_no, ['transaction_id', 'status', 'pay_time'], [
            'transaction_id' => $transaction_id,
            'status' => OrderEnum::PAY_SUCCESS,
            'pay_time' => time()
        ]);

        // 根据订单编号查询订单信息
        $orderData = OrderModel::getOrderDataByOrderNo($order_no, ['title', 'amount', 'allow_pay_subscribe', 'create_time'], true, ['virtual_product']);

        // 判断当前返回的附加数据上是否有数据
//        echo $attach;
        if (!empty($attach)) {
            $attach = json_decode($attach,true);
            print_r($attach);
            print_r($attach['type']);
            if (isset($attach['type'])) {
//                echo 'attach type value:' . $attach['type'] . PHP_EOL;
                // 判断当前附加数据的类型
                switch ($attach['type']) {
                    case OrderType::Shop_Order:
                        echo '开始处理图鸟商店成功支付订单' . PHP_EOL;
                        // 判断单曲订单的商品中是否有虚拟商品
                        $virtual_product = array_column($orderData['product'], 'virtual_product');
                        if (in_array(1, $virtual_product)) {
                            $orderData['virtual_product'] = 1;
                        } else {
                            $orderData['virtual_product'] = 0;
                        }
                        unset($orderData['product']);
                        // 如果是商店订单就通知管理员有用户下单成功
                        echo '开始发送用户支付成功消息给管理员' . PHP_EOL;
                        $this->sendUserPayShopOrderSuccessToAdmin($orderData);
                        // 订单销量加一
                        echo '开始对订单商品销量进行处理' . PHP_EOL;
                        ShopProduct::updateShopProductSalesVolume($orderData['id']);
                        // 删除订单微信支付的相关信息
                        echo '开始移除缓存相关数据' . PHP_EOL;
                        OrderModel::deleteTnShopWxPayOptionsFromCache($order_no);
                        break;
                }
            }

        }

        if ($is_send_template && $orderData['allow_pay_subscribe'] === 1) {
            (new OrderSubscribeMessage())->sendOrderSubscribeMessage(
                'pay',
                $orderData['user']['openid'],
                [
                    'order_no' => $orderData['order_no'],
                    'title' => $orderData['title'],
                    'amount' => $orderData['amount'],
                    'create_time' => $orderData['create_time']
                ]);
        }

        (new OrderModel())->db()->getConnection()->close();
        (new ShopProduct())->db()->getConnection()->close();
        return true;
    }

    /**
     * 用户订单支付成功后给后台管理员发送消息模版
     * @param $data
     */
    private function sendUserPayShopOrderSuccessToAdmin($data)
    {
//        $oc_admin_app_id = get_wx_config('oc_admin_open_id');
//        $oc_admin_app_id = get_wx_config('oc_development_open_id');

        $notify_id = [
            get_wx_config('oc_admin_open_id'),
            get_wx_config('oc_development_open_id')
        ];

        foreach ($notify_id as $id) {
            (new TNShopOrderNotifyTemplateMessage())->sendOrderNotifyTemplateMessage('pay_success',
                $id,
                [
                    'virtual_product' => $data['virtual_product'],
                    'order_no' => $data['order_no'],
                    'title' => $data['title'],
                    'amount' => $data['amount'],
                    'create_time' => $data['create_time'],
                    'remark' => '微信小商店第三方平台授权失效，请点击重新再次授权'
                ]);
        }
    }
}